#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
@File        :   19.删除链表的倒数第N个节点.py    
@Contact     :   lhouctcs@163.com
@License     :   MIT
@Time        :   2023/2/4 14:15
@Author      :   lhou 
@Version     :   0.1.0
@Description :
"""
from typing import Optional


# import lib
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


class Solution:
    def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
        num = 0
        tmp = head
        while tmp:
            tmp = tmp.next
            num += 1
        index = num - n
        root = ListNode(-1, head)
        node = root
        for _ in range(index):
            node = node.next
        node.next = node.next.next
        return root.next
